import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟API延迟
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

// 数据源类型选项
export const dbTypeOptions = [
  { value: 'mysql', label: 'MySQL' },
  { value: 'postgresql', label: 'PostgreSQL' },
  { value: 'sqlserver', label: 'SQL Server' },
  { value: 'oracle', label: 'Oracle' },
]

export const useDataSourceStore = defineStore('dataSource', () => {
  // 状态
  const sources = ref([])
  const loading = ref(false)
  const testingConnection = ref(false)

  // 初始化一些示例数据
  const initSampleData = async () => {
    loading.value = true
    await delay(500)

    sources.value = [
      {
        id: 1,
        name: '生产环境MySQL',
        description: '主数据库服务器',
        type: 'mysql',
        host: '192.168.1.100',
        port: 3306,
        database: 'production_db',
        username: 'admin',
        password: '******',
        enableSsl: false,
        status: 'connected',
        createTime: '2023-01-15 10:00:00',
        updateTime: '2023-06-20 14:30:00',
      },
      {
        id: 2,
        name: '测试PostgreSQL',
        description: '测试数据库服务器',
        type: 'postgresql',
        host: '192.168.1.101',
        port: 5432,
        database: 'test_db',
        username: 'test_user',
        password: '******',
        enableSsl: true,
        status: 'disconnected',
        createTime: '2023-02-10 11:20:00',
        updateTime: '2023-06-15 09:45:00',
      },
      {
        id: 3,
        name: '开发Oracle',
        description: '开发环境数据库',
        type: 'oracle',
        host: '192.168.1.102',
        port: 1521,
        database: 'DEV',
        username: 'dev_user',
        password: '******',
        enableSsl: false,
        status: 'connected',
        createTime: '2023-03-05 16:40:00',
        updateTime: '2023-05-20 13:15:00',
      },
    ]

    loading.value = false
  }

  // 获取数据源列表
  const fetchSources = async () => {
    if (sources.value.length === 0) {
      await initSampleData()
    }
    return sources.value
  }

  // 获取单个数据源
  const getSourceById = (id) => {
    return sources.value.find((source) => source.id === id)
  }

  // 创建数据源
  const createSource = async (sourceData) => {
    loading.value = true
    await delay(800)

    const newSource = {
      ...sourceData,
      id: sources.value.length + 1,
      status: 'disconnected',
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString(),
    }

    sources.value.push(newSource)
    loading.value = false

    ElMessage.success('数据源创建成功')
    return newSource
  }

  // 更新数据源
  const updateSource = async (id, sourceData) => {
    loading.value = true
    await delay(800)

    const index = sources.value.findIndex((source) => source.id === id)
    if (index !== -1) {
      sources.value[index] = {
        ...sources.value[index],
        ...sourceData,
        updateTime: new Date().toLocaleString(),
      }

      loading.value = false
      ElMessage.success('数据源更新成功')
      return sources.value[index]
    }

    loading.value = false
    ElMessage.error('未找到数据源')
    return null
  }

  // 删除数据源
  const deleteSource = async (id) => {
    loading.value = true
    await delay(600)

    const index = sources.value.findIndex((source) => source.id === id)
    if (index !== -1) {
      sources.value.splice(index, 1)
      loading.value = false
      ElMessage.success('数据源删除成功')
      return true
    }

    loading.value = false
    ElMessage.error('未找到数据源')
    return false
  }

  // 测试连接
  const testConnection = async (sourceData) => {
    testingConnection.value = true
    await delay(1500)

    // 模拟连接测试结果
    const success = Math.random() > 0.3

    testingConnection.value = false

    if (success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败，请检查连接信息')
    }

    return success
  }

  // 根据ID测试连接
  const testConnectionById = async (id) => {
    const source = getSourceById(id)
    if (source) {
      return await testConnection(source)
    }
    return false
  }

  // 计算属性
  const sourceOptions = computed(() => {
    return sources.value.map((source) => ({
      value: source.id,
      label: source.name,
    }))
  })

  return {
    sources,
    loading,
    testingConnection,
    fetchSources,
    getSourceById,
    createSource,
    updateSource,
    deleteSource,
    testConnection,
    testConnectionById,
    sourceOptions,
  }
})
